<?php
class MY_Model extends CI_Model
{
	function __construct()
	{
		parent::__construct();
		
		
		// Get Error Message
		$row	= $this->MessageTemplate("CS001");
		$this->success_insert	= ($row == NULL ? '' : $row['message']);
		
		$row	= $this->MessageTemplate("CS002");
		$this->success_update	= ($row == NULL ? '' : $row['message']);
		
		$row	= $this->MessageTemplate("CS003");
		$this->success_delete	= ($row == NULL ? '' : $row['message']);
		
		$row	= $this->MessageTemplate("ER012");
		$this->error_delete		= ($row == NULL ? '' : $row['message']);
		
		
		// Get Session Menu Id
		$sess_data	= $this->session->all_userdata();
		if(is_array($sess_data) && array_key_exists('session_menu_id',$sess_data) ){
			$this->session_menu_id = $sess_data['session_menu_id'];
		}else{
			$this->session_menu_id = '';
		}
	}
	
	function web_option($option_name='', $option_value=''){
		if(trim($option_value)!=''){
			$this->db->update(	'IT_CONFIG', 
								array(	'CONFIG_VALUE'	=> (is_array($option_value) ? json_encode($option_value) : $option_value)), 
								array(	'APP_ID'		=> (defined('CURRENT_APP') && CURRENT_APP != ''  ? CURRENT_APP : 'CORE'), 
										'CONFIG_NAME'	=> $option_name)); 
		} else {
			$value	= $this->get_data("SELECT CONFIG_VALUE FROM IT_CONFIG WHERE APP_ID = '".(defined('CURRENT_APP') && CURRENT_APP != ''  ? CURRENT_APP : 'CORE')."' AND CONFIG_NAME = '".$option_name."'");
			if(@strstr($value,'[')!='' || @strstr($value,'{')!=''){ $value = json_decode($value); }
			return $value;
		}
	}
	
	function get_data($sql_string){
		$result = $this->db->query($sql_string);
		$arr_data = $result->result_array();
		
		if(count($arr_data)==0){
			return '';
		}else{
			$row		= $arr_data[0];
			$array_key	= array_keys($row);
			
			if(count($array_key)==0){
				return '';
			}else{
				$key	= $array_key[0];
				return $row[$key];
			}
		}
	}
	
	function paging_start(){
		$this->db->start_cache();
	}
	
	function paging_stop(){
		$this->db->stop_cache();
	}
	
	function paging($ls_sql){
		// Explode SQL Statement into array [SELECT, FROM, WHERE, ORDER BY]
		$tmp = ''; 
		$itter_after_reset	= 0;
		$itter_bracket		= 0;
		$keyword_position	= '';
		$arr_word			= array();
		$arr_keyword_query	= array('SELECT' => '', 'FROM' => '', 'WHERE' => '', 'ORDER BY' => '');
		$st_cutword			= false;
		for($i=0,$max_i=strlen($ls_sql); $i<=$max_i; $i++){
			$char = ($i==$max_i ? ' ' : substr($ls_sql, $i, 1));
			if($char == '('){ $itter_bracket++; }else if($char==')'){ $itter_bracket--; }
			
			if(in_array($char, array(' ','	',chr(10),chr(13)))){
				if($itter_after_reset == 0){ $word = $tmp; $arr_word = array_merge($arr_word, array($word)); }
				$itter_after_reset++; $tmp = '';
				$st_cutword = true;
			}else{
				$word = '';
				$tmp .= $char;
				$itter_after_reset = 0;
				$st_cutword = false;
			}
			
			
			if(strtoupper($word)=='SELECT' && $itter_bracket==0){ $keyword_position = 'SELECT'; }
			else if(strtoupper($word)=='FROM' && $itter_bracket==0){ $keyword_position = 'FROM'; }
			else if(strtoupper($word)=='WHERE' && $itter_bracket==0){ $keyword_position = 'WHERE'; }
			else if(strtoupper($word)=='BY' && $arr_word[count($arr_word)-2] == 'ORDER' && $itter_bracket==0){ $keyword_position = 'ORDER BY'; }
			
			
			if($keyword_position=='SELECT'){
				$arr_keyword_query['SELECT'] .= (($st_cutword && $itter_after_reset<=1) || !$st_cutword ? $char : '');
			}else if($keyword_position=='FROM'){
				$arr_keyword_query['FROM'] .= (($st_cutword && $itter_after_reset<=1) || !$st_cutword ? $char : '');
			}else if($keyword_position=='WHERE'){
				$arr_keyword_query['WHERE'] .= (($st_cutword && $itter_after_reset<=1) || !$st_cutword ? $char : '');
			}else if($keyword_position=='ORDER BY'){
				$arr_keyword_query['ORDER BY'] .= (($st_cutword && $itter_after_reset<=1) || !$st_cutword ? $char : '');
			}
		}
		$arr_keyword_query['SELECT'] = trim($arr_keyword_query['SELECT']);
		$arr_keyword_query['FROM'] = trim($arr_keyword_query['FROM']);
		$arr_keyword_query['WHERE'] = trim($arr_keyword_query['WHERE']);
		$arr_keyword_query['ORDER BY'] = trim($arr_keyword_query['ORDER BY']);
		
		$arr_keyword_query['SELECT'] = trim(substr($arr_keyword_query['SELECT'],0,strlen($arr_keyword_query['SELECT'])-4));
		if($arr_keyword_query['WHERE'] != ''){
			$arr_keyword_query['FROM'] = trim(substr($arr_keyword_query['FROM'],0,strlen($arr_keyword_query['FROM'])-5));
		}
		if($arr_keyword_query['WHERE'] != '' && $arr_keyword_query['ORDER BY'] != ''){
			$arr_keyword_query['WHERE'] = trim(substr($arr_keyword_query['WHERE'],0,strlen($arr_keyword_query['WHERE'])-8));
		}
		
		
		// Get Necessary Variable For Paging
		$perpage	= intval(post('rows')) > 0 ? intval(post('rows')) : $this->web_option("DATA_PER_PAGE");
		$total = $this->get_data("	SELECT COUNT(1) 
									FROM ".$arr_keyword_query['FROM']." ".
									($arr_keyword_query['WHERE']!="" ? "WHERE ".$arr_keyword_query['WHERE'] : ""));
		$cur_page = ((post('page') > ceil($total/$perpage)) ? ceil($total/$perpage) : (post('page') < 1 ? 1 : post('page')));
		if($cur_page < 1) $cur_page = 1;
		
		
		// Set Start & End Rows
		$ln_start	= (($cur_page - 1) * $perpage) + 1;
		$ln_end		= $ln_start + $perpage - 1;
		
		// Patching For oracle
		$arr_keyword_query['SELECT']	= (trim($arr_keyword_query['SELECT']) == '*' ? $arr_keyword_query['FROM'].'.' : '') . $arr_keyword_query['SELECT'];
		
		// Create New SQL with Paging
		$ls_sql_with_paging	= "	SELECT * 
								FROM (
										SELECT ".$arr_keyword_query['SELECT'].", ROW_NUMBER() OVER (ORDER BY ".$arr_keyword_query['ORDER BY'].") AS xrownum
										FROM ".$arr_keyword_query['FROM']." 
										".($arr_keyword_query['WHERE']!="" ? "WHERE ".$arr_keyword_query['WHERE'] : "").") tbl
								WHERE	xrownum BETWEEN ".$ln_start." AND ".$ln_end."
								ORDER BY xrownum";
		
		$result	= $this->db->query($ls_sql_with_paging);
		$arr_data = $result->result_array();
		$result->free_result();					
		
		
		// Create Array Response For Datagrid
		$arr_response = array(	'rows'=> $arr_data, 
								'total' => $total, 
								'page'=>$cur_page,
								//'next'=>($total==0 || post('page')==(ceil($total/$perpage)) ? 0 : post('page')+1), 
								'sessid'=> _SESSID);
								
		return $arr_response;
	}
	
	function GetWebOptionCulture(){
		$arr_culture_option	= explode(',', $this->web_option('culture_option'));
		
		$this->db->select('culture_id, culture_name');
		$this->db->from('sw_culture');
		$this->db->where_in('culture_id', $arr_culture_option);
		$this->db->order_by('st_default', 'desc');
		$result	= $this->db->get();
		
		if($result->num_rows() > 0){
			return $result->result_array();
		}else{
			return NULL;
		}
	}
	
	function MessageTemplate($code)
	{
		$this->db->select('*');
		$this->db->from('IT_SYSTEM_MESSAGE');
		$this->db->where('CODE', $code);
		
		$result = $this->db->get();
		if($result->num_rows()==1){
			$arr_data	= $result->row_array();
			return $arr_data;
		}else{
			return NULL;
		}
	}
	
	function AuditTrail($table_name, $action, $primary_key, $reason='', $desc=''){
		if(strlen($primary_key)>100){ $primary_key = substr($primary_key,0,100); }
		$this->db->insert(	'IT_AUDIT_TRAIL', 
							array(	'LOG_ID'		=> $this->get_data("SELECT NVL((SELECT MAX(LOG_ID) FROM IT_AUDIT_TRAIL),0)+1 create_id FROM DUAL"),
									'TABLE_NAME'	=> $table_name, 
									'USER_ID'		=> USERID, 
									'EVENT_DATE'	=> NOW, 
									'ACTION'		=> $action,
									'PRIMARY_KEY'	=> $primary_key,
									'MENU_ID'		=> $this->session_menu_id,
									'REASON'		=> $reason,
									'AUDIT_DESC'	=> $desc,
									'CREATE_DATE'	=> NOW,
									'CREATE_USER'	=> USERID));
	}
} 
?>